package tenglang.common.utils;


import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * SHA256 摘要算法工具类
 * 
 * @author Administrator
 *
 */
public class SHA256Util {
	
	public final static String CLIENT_SEND_TIME="clientSendTime";
	public final static String RANDOM_NUMBER="randomNumber";
	public final static String CONTENT="content";
	public final static String ACCEPT_USER_ID="acceptUserId";
	
	public final static String FROM_USER_ID="fromUserId";
	public final static String SEND_TIME="randomNumber";
	
    private static String receiveParamsSHA256Str="{clientSendTime}#{randomNumber}#{content}#{acceptUserId}";
    private static String sendParamsSHA256Str="{sendTime}#{fromUserId}#{content}#{acceptUserId}";
    	
	public static void main(String[] args) throws Exception {
//		String s=getSHA256StrJava("Message","salt");
//		System.out.println(s);
		
		String s=getMd5StrJava("wangjun","123456","860919");
		System.out.println(s);
		
		String ss=getMd5StrJava("zhangsan","123456","860919");
		System.out.println(ss);
		
		String ss3=getMd5StrJava("guoqi","123456","860919");
		System.out.println(ss3);
		
		String s4=getMd5StrJava("geba","123456","860919");
		System.out.println(s4);
		
		/*String sss=getSHA256StrJava("wangjun","123");
		System.out.println(sss);*/
	}

	public static String getSHA256StrJava(String str,String key) throws Exception {
	     Mac sha256_HMAC=null;
		try {
			sha256_HMAC = Mac.getInstance("HmacSHA256");
			SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("utf-8"), "HmacSHA1");
		     sha256_HMAC.init(secret_key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return byte2Hex(sha256_HMAC.doFinal(str.getBytes("utf-8")));
	}
	
	
	public static String getSHA256StrJava(Map<String,Object> params,String key,boolean isReceive){
	     Mac sha256_HMAC=null;
	     Iterator<Entry<String, Object>> paramsIterator=params.entrySet().iterator();
		 String source=isReceive?sendParamsSHA256Str:receiveParamsSHA256Str;
		 while(paramsIterator.hasNext()) {
				Entry<String, Object> paramsEntry=paramsIterator.next();
				source=source.replace("{"+paramsEntry.getKey()+"}", String.valueOf(paramsEntry.getValue()));
		}
		byte[] sourceBytes=null;
		try {
			sha256_HMAC = Mac.getInstance("HmacSHA256");
			SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("utf-8"), "HmacSHA1");
		     sha256_HMAC.init(secret_key);
		     sourceBytes=source.getBytes("utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return byte2Hex(sha256_HMAC.doFinal(sourceBytes));
	}
	
	public static String getSHA256StrJava(Map<String,String> params,String[] keys,String masterKey){
		 StringBuffer keyBuffer=new StringBuffer();
		 for(String key:keys) {
			 if(!key.equalsIgnoreCase(masterKey)) {
				 keyBuffer.append("{"+key+"}#");
			 }
		 }
		 keyBuffer.deleteCharAt(keyBuffer.length()-1);
		 String source=keyBuffer.toString();
	     Mac sha256_HMAC=null;
	     Iterator<Entry<String, String>> paramsIterator=params.entrySet().iterator();
		 while(paramsIterator.hasNext()) {
				Entry<String, String> paramsEntry=paramsIterator.next();
				source=source.replace("{"+paramsEntry.getKey()+"}", String.valueOf(paramsEntry.getValue()));
		 }
		 String masterKeyValue=params.get(masterKey);
		byte[] sourceBytes=null;
		try {
			sha256_HMAC = Mac.getInstance("HmacSHA256");
			SecretKeySpec secret_key = new SecretKeySpec(masterKeyValue.getBytes("utf-8"), "HmacSHA1");
		    sha256_HMAC.init(secret_key);
		    sourceBytes=source.getBytes("utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return byte2Hex(sha256_HMAC.doFinal(sourceBytes));
	}
	
	public static String getMd5StrJava(String str,String key,String salt){
	     Mac shaHmacMD5=null;
		try {
			SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("utf-8"), "HmacMD5");
			shaHmacMD5 = Mac.getInstance(secret_key.getAlgorithm());
			shaHmacMD5.init(secret_key);
			shaHmacMD5.update(salt.getBytes("utf-8"));
			return byte2Hex(shaHmacMD5.doFinal(str.getBytes("utf-8")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将byte转为16进制
	 * 
	 * @param bytes
	 * @return
	 */
	private static String byte2Hex(byte[] a) {
		 int hn, ln, cx;
	        String hexDigitChars = "0123456789abcdef";
	        StringBuffer buf = new StringBuffer(a.length * 2);
	        for(cx = 0; cx < a.length; cx++) {
	            hn = ((int)(a[cx]) & 0x00ff) /16 ;
	            ln = ((int)(a[cx]) & 0x000f);
	            buf.append(hexDigitChars.charAt(hn));
	            buf.append(hexDigitChars.charAt(ln));
	        }
		return buf.toString();
	}

}